// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Data;
using System.Data.SqlClient;
using InterpriseSuiteEcommerceCommon.Extensions;

namespace InterpriseSuiteEcommerceCommon.DTO
{
    public class KitItemData
    {
        public int Counter;
        public string ItemCode;
        private KitGroupDataCollection _groups = new KitGroupDataCollection();

        public KitGroupDataCollection Groups
        {
            get { return _groups; }
        }

        #region GetKitComposition

        public static KitItemData GetKitComposition(Customer thisCustomer, int itemCounter, string itemKitCode)
        {
            bool weAreInEditMode =
            !(CommonLogic.QueryStringCanBeDangerousContent("kcid").IsNullOrEmptyTrimmed()) &&
            InterpriseHelper.IsValidGuid(CommonLogic.QueryStringCanBeDangerousContent("kcid"));

            Guid cartId = Guid.Empty;
            if (weAreInEditMode)
            {
                cartId = new Guid(CommonLogic.QueryStringCanBeDangerousContent("kcid"));
            }

            // NOTE:
            //  In interprise, the kit details is defined to whatever is set on the Currency on the Selling Language
            //  If the current customer's currency is not 
            bool isCustomerCurrencyIncludedForInventorySelling = InterpriseHelper.IsCurrencyIncludedForInventorySelling(thisCustomer.CurrencyCode);

            // Special case 2 
            //  Currency is added in Inventory Selling Currency late
            //  after the kit has been created, ideally the kit should regenerate kit pricing for this currency
            //  but for the meantime, we should handle this by looking into the home currency
            bool currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem =
            InterpriseHelper.CurrencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYet(thisCustomer.CurrencyCode, itemKitCode);

            // if the currency is not included in the selling currencies for inventory
            // then get the rates for the Base currency -- The convert the exchange rate
            string lookupCurrency = string.Empty;
            // the current exchange rate if we should convert
            decimal exchangeRate = decimal.Zero;
            if (isCustomerCurrencyIncludedForInventorySelling &&
                !currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem)
            {
                lookupCurrency = thisCustomer.CurrencyCode;
            }
            else
            {
                lookupCurrency = Currency.GetHomeCurrency();
                exchangeRate = Currency.GetExchangeRate(thisCustomer.CurrencyCode);
            }

            // build kit item info...
            string kitInfoQuery =
                    String.Format(
                        "exec EcommerceGetKitItems   @ItemKitCode = {0}, @CurrencyCode = {1}, @LanguageCode = {2}, @CustomerCode = {3}, @CartID = {4}, @WebsiteCode = {5}, @IsAnonymous = {6}, @AnonymousCustomerCode = {7}, @ContactCode = {8}",
                        itemKitCode.ToDbQuote(),
                        lookupCurrency.ToDbQuote(),
                        thisCustomer.LanguageCode.ToDbQuote(),
                        (thisCustomer.CustomerCode.IsNullOrEmptyTrimmed())? "null": thisCustomer.CustomerCode.ToDbQuote(),
                        (weAreInEditMode)? cartId.ToString().ToDbQuote(): "null",
                        InterpriseHelper.ConfigInstance.WebSiteCode.ToDbQuote(),
                        (thisCustomer.IsNotRegistered)? 1: 0,
                        thisCustomer.AnonymousCustomerCode.ToDbQuote(),
                        thisCustomer.ContactCode.ToDbQuote()
                    );

            var kit = new KitItemData() 
            {
                Counter = itemCounter,
                ItemCode = itemKitCode
            };

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, kitInfoQuery))
                {
                    while (reader.Read())
                    {
                        string itemCode = DB.RSField(reader, "ItemCode");
                        string itemName = DB.RSField(reader, "ItemName");
                        string itemType = DB.RSField(reader, "ItemType");
                        int itemId = DB.RSFieldInt(reader, "ItemId");
                        decimal totalRate = DB.RSFieldDecimal(reader, "TotalRate");
                        bool isDefault = DB.RSFieldBool(reader, "IsDefault");
                        bool select = DB.RSFieldBool(reader, "Select");
                        string groupCode = DB.RSField(reader, "GroupCode");
                        string groupType = DB.RSField(reader, "GroupType");
                        int groupId = DB.RSFieldInt(reader, "GroupId");
                        string groupDescription = DB.RSField(reader, "GroupDescription");
                        string groupHTMLDescription = DB.RSField(reader, "GroupHTMLDescription");
                        string selectionControl = DB.RSField(reader, "SelectionControl");
                        string unitMeasureCode = DB.RSField(reader, "UnitMeasureCode");
                        decimal freeStock = DB.RSFieldDecimal(reader, "FreeStock");

                        if (!DB.RSField(reader, "ItemDescription").IsNullOrEmptyTrimmed())
                        {
                            itemName = DB.RSField(reader, "ItemDescription");
                        }

                        if (!groupHTMLDescription.IsNullOrEmptyTrimmed())
                        {
                            groupHTMLDescription = CommonLogic.ExtractBody(groupHTMLDescription, false);
                        }

                        KitGroupData kitGroup = null;

                        if (!kit.Groups.Contains(groupId))
                        {
                            kitGroup = new KitGroupData()
                            {
                                Id = groupId,
                                Code = groupCode,
                                Type = groupType
                            };

                            kitGroup.Description = (!groupHTMLDescription.IsNullOrEmptyTrimmed())? groupHTMLDescription: groupDescription;
                            var currencyFormat = Currency.GetCurrencyFormat(thisCustomer.CurrencyCode);
                            kitGroup.CurrencySymbol = currencyFormat.CurrencySymbol;

                            kitGroup.ControlType = selectionControl;
                            kit.Groups.Add(kitGroup);
                        }

                        kitGroup = kit.Groups[groupId];

                        var item = new KitItem()
                        {
                            Code = itemCode,
                            Name = itemName,
                            IsSelected = select,
                            Id = itemId,
                            Type = itemType
                        };

                        var priceAndUnitMeasure = new ProductPricePerUnitMeasure(unitMeasureCode)
                        {
                            hasPromotionalPrice = false,
                            promotionalPrice = Decimal.Zero,
                            freeStock = freeStock
                        };

                        decimal price = Decimal.Zero;
                        if (isCustomerCurrencyIncludedForInventorySelling &&
                               !currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem)
                        {
                            price = totalRate;
                        }
                        else
                        {
                            price = Interprise.Facade.Base.SimpleFacade.Instance.ConvertCurrency(
                                        exchangeRate, totalRate, false, thisCustomer.CurrencyCode, Interprise.Framework.Base.Shared.Enum.CurrencyFormat.Total);
                        }

                        priceAndUnitMeasure.price = price;
                        priceAndUnitMeasure.priceFormatted = thisCustomer.FormatBasedOnMyCurrency(price);
                        item.UnitMeasures.Add(priceAndUnitMeasure);

                        kitGroup.Items.Add(item);
                    }
                }
            }

            return kit;
        }

        public static KitItemData GetKitCompositionForGiftRegistry(Customer thisCustomer, int itemCounter, string itemKitCode, Guid giftRegistryID, Guid registryItemCode)
        {
            // NOTE:
            //  In interprise, the kit details is defined to whatever is set on the Currency on the Selling Language
            //  If the current customer's currency is not 
            bool isCustomerCurrencyIncludedForInventorySelling = InterpriseHelper.IsCurrencyIncludedForInventorySelling(thisCustomer.CurrencyCode);

            // Special case 2 
            //  Currency is added in Inventory Selling Currency late
            //  after the kit has been created, ideally the kit should regenerate kit pricing for this currency
            //  but for the meantime, we should handle this by looking into the home currency
            bool currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem =
            InterpriseHelper.CurrencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYet(thisCustomer.CurrencyCode, itemKitCode);

            // if the currency is not included in the selling currencies for inventory
            // then get the rates for the Base currency -- The convert the exchange rate
            string lookupCurrency = String.Empty;
            // the current exchange rate if we should convert
            decimal exchangeRate = Decimal.Zero;
            if (isCustomerCurrencyIncludedForInventorySelling &&
                !currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem)
            {
                lookupCurrency = thisCustomer.CurrencyCode;
            }
            else
            {
                lookupCurrency = Currency.GetHomeCurrency();
                exchangeRate = Currency.GetExchangeRate(thisCustomer.CurrencyCode);
            }

            // build kit item info...
            string kitInfoQuery = String.Format("exec EcommerceGetKitItemsForGiftRegistry @ItemKitCode = {0}, @CurrencyCode = {1}, @LanguageCode = {2}, @Giftregistryid = {3}, @RegistryItemCode = {4} ",
                                                itemKitCode.ToDbQuote(),
                                                lookupCurrency.ToDbQuote(),
                                                thisCustomer.LanguageCode.ToDbQuote(),
                                                giftRegistryID.ToString().ToDbQuote(),
                                                registryItemCode.ToString().ToDbQuote()
            );

            var kit = new KitItemData()
            {
                Counter = itemCounter,
                ItemCode = itemKitCode
            };

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, kitInfoQuery))
                {
                    while (reader.Read())
                    {
                        string itemCode = DB.RSField(reader, "ItemCode");
                        string itemName = DB.RSField(reader, "ItemName");
                        string itemType = DB.RSField(reader, "ItemType");
                        int itemId = DB.RSFieldInt(reader, "ItemId");
                        decimal totalRate = DB.RSFieldDecimal(reader, "TotalRate");
                        bool isDefault = DB.RSFieldBool(reader, "IsDefault");
                        bool select = DB.RSFieldBool(reader, "Select");
                        string groupCode = DB.RSField(reader, "GroupCode");
                        string groupType = DB.RSField(reader, "GroupType");
                        int groupId = DB.RSFieldInt(reader, "GroupId");
                        string groupDescription = DB.RSField(reader, "GroupDescription");
                        string groupHTMLDescription = DB.RSField(reader, "GroupHTMLDescription");
                        string selectionControl = DB.RSField(reader, "SelectionControl");
                        string unitMeasureCode = DB.RSField(reader, "UnitMeasureCode");

                        if (!DB.RSField(reader, "ItemDescription").IsNullOrEmptyTrimmed())
                        {
                            itemName = DB.RSField(reader, "ItemDescription");
                        }

                        if (!groupHTMLDescription.IsNullOrEmptyTrimmed())
                        {
                            groupHTMLDescription = CommonLogic.ExtractBody(groupHTMLDescription, false);
                        }

                        KitGroupData kitGroup = null;
                        if (!kit.Groups.Contains(groupId))
                        {
                            kitGroup = new KitGroupData()
                            {
                                Id = groupId,
                                Code = groupCode,
                                Type = groupType
                            };

                            kitGroup.Description = (!CommonLogic.IsStringNullOrEmpty(groupHTMLDescription))? groupHTMLDescription: groupDescription;
                            kitGroup.ControlType = selectionControl;
                            kit.Groups.Add(kitGroup);
                        }

                        kitGroup = kit.Groups[groupId];

                        var item = new KitItem()
                        {
                            Code = itemCode,
                            Name = itemName,
                            IsSelected = select,
                            Id = itemId,
                            Type = itemType
                        };

                        var priceAndUnitMeasure = new ProductPricePerUnitMeasure(unitMeasureCode)
                        {
                            hasPromotionalPrice = false,
                            promotionalPrice = decimal.Zero
                        };

                        decimal price = decimal.Zero;
                        if (isCustomerCurrencyIncludedForInventorySelling &&
                               !currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem)
                        {
                            price = totalRate;
                        }
                        else
                        {
                            price = Interprise.Facade.Base.SimpleFacade.Instance.ConvertCurrency(exchangeRate, totalRate, false, thisCustomer.CurrencyCode, Interprise.Framework.Base.Shared.Enum.CurrencyFormat.Total);
                        }

                        priceAndUnitMeasure.price = price;
                        priceAndUnitMeasure.priceFormatted = thisCustomer.FormatBasedOnMyCurrency(price);
                        item.UnitMeasures.Add(priceAndUnitMeasure);

                        kitGroup.Items.Add(item);
                    }
                }
            }

            return kit;
        }

        #endregion
    }
    
}



